/**
 * 
 */
package org.totalbeginner.tutorial;

import static org.junit.Assert.*;

import java.io.File;

import org.junit.Test;

/**
 * @author ibraheem.abdullah
 *
 */
public class MyUtilitiesTest {

	@Test
	public void saveStringToFile() {
		String szToSave = "This is the first line in file to save \n" +
							"This is the second line in the same file to save.\n";
		File myFile = new File("simpleFile.txt");
		myFile.delete();
		assertFalse("The file should be deleted...",myFile.exists());
		
		assertTrue("Message written successfuly...", 
					MyUtilities.saveStringToFile("simpleFile.txt",szToSave));
		
		assertTrue("Written string should match the original one after reading... "
					, szToSave.equals(MyUtilities.getStringFromFile("simpleFile.txt")));
		
		assertFalse("Message should not be written to wrong filepath...", 
				MyUtilities.saveStringToFile("wrongDirectory\\simplewrongFile.txt",szToSave));
		
		szToSave = "";
		assertTrue("Message should be empty from a wrong file... "
				, szToSave.equals(MyUtilities.getStringFromFile("simplewrongFile.txt")));
	}
	
	public MyLibrary createMyLibrary() {
		MyLibrary m1;
		Book b1;
		Book b2;
		Person p1;
		Person p2;
		m1 = new MyLibrary("Test Lib");
		b1 = new Book("Book1");
		b2 = new Book("Book2");
		p1 = new Person();
		p2 = new Person();
		p1.setName("IbrABD");
		p2.setName("Qud");	
		m1.addBook(b1);
		m1.addBook(b2);
		m1.addPerson(p1);
		m1.addPerson(p2);
		m1.checkout(b1, p1);
		return m1;
	}

	@Test
	public void ConvertToXML(){
		MyLibrary myLibStart = createMyLibrary();
		String szXMLMyLib = MyUtilities.convertToXML(myLibStart);
		MyLibrary myLibEnd = MyUtilities.convertFromXML(szXMLMyLib);
		assertEquals("Test Lib", myLibEnd.getName());
		assertEquals(2, myLibEnd.getBooks().size());
		assertEquals(2, myLibEnd.getPeople().size());
		assertEquals("IbrABD", myLibEnd.getBooks().get(0).getPerson().getName());
		
	}
	
	@Test
	public void SetLibrary(){
		MyLibrary myLibStart = createMyLibrary();
		assertTrue("File should be saved by now...",MyUtilities.saveMyLibrary("simpleFile.xml", myLibStart));
		MyLibrary myLibEnd = MyUtilities.loadMyLibrary("simpleFile.xml");
		assertEquals("Test Lib", myLibEnd.getName());
		assertEquals(2, myLibEnd.getBooks().size());
		assertEquals(2, myLibEnd.getPeople().size());
		assertEquals("IbrABD", myLibEnd.getBooks().get(0).getPerson().getName());
	}
}
